package com.ideaaedi.commonspring.filter;

import com.alibaba.fastjson2.filter.ValueFilter;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 忽略指定类型的值
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 2100.10.16.LTS17
 */
public class JsonIgnoreValueFilter implements ValueFilter {

    @Nonnull
    private final Set<Class<?>> ignoreTypesSet;

    public JsonIgnoreValueFilter(@Nullable Class<?>... ignoreTypes) {
        if (ignoreTypes == null || ignoreTypes.length == 0) {
            ignoreTypesSet = Collections.emptySet();
        } else {
            this.ignoreTypesSet = Arrays.stream(ignoreTypes).collect(Collectors.toSet());
        }
    }

    @Override
    public Object apply(Object object, String name, Object value) {
        if (value == null || CollectionUtils.isEmpty(ignoreTypesSet)) {
            return value;
        }
        Class<?> hitIgnoreTypeClass = ignoreTypesSet.stream()
                .filter(x -> ClassUtils.isAssignable(x, value.getClass()))
                .findFirst()
                .orElse(null);
        if (hitIgnoreTypeClass == null) {
            return value;
        }
        return "<hit ignore type '" + hitIgnoreTypeClass.getName() + "'>";
    }
}
